import {
  EMITS_SLIDERCAPTCHA_CLOSE,
  EMITS_SLIDERCAPTCHA_SUCCESS
} from '@/constants/events';
import { ref, type Ref } from 'vue';
import { useRouter } from 'vue-router';

export default function useCaptcha(params: {
  onLogin: (form: {
    username: string;
    password: string;
    loginType?: 'username';
  }) => Promise<void>;
  loginForm: Ref<{
    username: string;
    password: string;
    loginType?: 'username';
  }>;
  isLoading: Ref<boolean>;
}) {
  const router = useRouter();
  const isSliderCaptchaVisible = ref<boolean>(false);

  const captchaEvents = {
    [EMITS_SLIDERCAPTCHA_SUCCESS]: async () => {
      isSliderCaptchaVisible.value = false;

      try {
        await params.onLogin(params.loginForm.value);
      } catch (error) {
        console.log(error);
      } finally {
        params.isLoading.value = false;
      }

      router.push({
        path: '/'
      });
    },
    [EMITS_SLIDERCAPTCHA_CLOSE]: () => (isSliderCaptchaVisible.value = false)
  };

  return {
    isSliderCaptchaVisible,
    captchaEvents
  };
}
